<?php

namespace Douyin;

class douyin
{

    /**
     * 获取抖音无水印原视频
     *
     * @param [type] $link
     * @return void
     */
    public static function original_video($link)
    {
        preg_match("/[a-zA-z]+:\/\/v.douyin.com\/[^\s]*/", $link, $url);
        if (!$url) {
            return [
                'status' => 0,
                'msg' => '链接提取失败，请检查链接是否正确。'
            ];
        }
        preg_match_all("/itemId: \"([0-9]+)\"|dytk: \"(.*)\"/", self::douyin_curl($url[0]), $res, PREG_SET_ORDER);
        if (!@$res[0][1] || !@$res[1][2]) {
            return [
                'status' => 0,
                'msg' => '链接解析失败，请稍后重试。'
            ];
        }
        $arr = json_decode(self::douyin_curl("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids={$res[0][1]}&dytk={$res[1][2]}"), true);
        return [
            'status' => 1,
            'data' => [
                'title'    => $arr['item_list'][0]['desc'],
                'img'      => $arr['item_list'][0]['video']['cover']['url_list'][0],
                'video' => self::douyin_curl(str_replace('playwm', 'play', $arr['item_list'][0]['video']['play_addr']['url_list'][0]), true),
                'music' => isset($arr['item_list'][0]['music']['play_url']['url_list'][0]) ? $arr['item_list'][0]['music']['play_url']['url_list'][0] : ''
            ]
        ];
    }

    /**
     * 抖音curl
     *
     * @param [type] $url
     * @param boolean $getinfo
     * @return void
     */
    public static function douyin_curl($url, $getinfo = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'));
        if ($getinfo) {
            curl_exec($ch);
            $data = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        } else {
            $data = curl_exec($ch);
        }
        curl_close($ch);
        return $data;
    }
}
